import 'package:flutter/material.dart';
import '../http/core/hi_net_error.dart';
import '../http/dio/login_dao.dart';
import '../navigator/hi_navigator.dart';
import '../util/string_util.dart';
import '../util/toast.dart';
import '../widget/appbar.dart';
import '../widget/login_button.dart';
import '../widget/login_effect.dart';
import '../widget/login_input.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  var protect = false;
  bool loginEnable = false;
  String? userName;
  String? password;
  String? rePassword;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar("注册", "登录", () => HiNavigator.getInstance.onJumpTo(RouteStatus.login)),
      body: Container(
        child: ListView(
          children: [
            LoginEffect(protect: protect),
            LoginInput("用户名", "请输入用户名", onChanged: (value) {
              userName = value;
              checkInput();
            }),
            LoginInput("密码", "请输入密码", obscureText: true, onChanged: (value) {
              password = value;
              checkInput();
            }, focusChanged: (focus) {
              setState(() {
                protect = focus;
              });
            }),
            LoginInput("确认密码", "请再次输入密码", obscureText: true, onChanged: (value) {
              rePassword = value;
              checkInput();
            }, focusChanged: (focus) {
              setState(() {
                protect = focus;
              });
            }),
            Padding(
                padding: const EdgeInsets.all(20),
                child: LoginButton("注册", enable: loginEnable, onPressed: checkParams))
          ],
        ),
      ),
    );
  }

  void checkInput() {
    setState(() {
      loginEnable = isNotEmpty(userName) && isNotEmpty(password) && isNotEmpty(rePassword);
    });
  }

  void checkParams() {
    String? tips;
    if (password != rePassword) {
      tips = '两次密码不一致';
    }
    if (tips != null) {
      showWarnToast(tips);
      return;
    }
    send();
  }

  void send() async {
    try {
      var result = await LoginDao.register(userName!, password!, "222", "333");
      print("loginRequest result: $result");
      if (result['code'] == 0) {
        print('注册成功');
        showToast('注册成功');
      } else {
        print(result['msg']);
        showWarnToast(result['msg']);
      }
    } on NeedAuth catch (e) {
      print(e);
      showWarnToast("注册失败：${e.message}");
    } on NeedLogin catch (e) {
      print(e);
      showWarnToast("注册失败：${e.message}");
    } on HiNetError catch (e) {
      print(e);
      showWarnToast("注册失败：${e.message}");
    }
  }
}
